import axios from 'axios'
// import type { AxiosRequestConfig, AxiosError, AxiosResponse } from 'axios'
import { ElMessage } from 'element-plus'
// import { GlobalStore } from '@/store/modules/global'
console.log('import.meta.env.VITE_BASE_URL', import.meta.env.VITE_BASE_URL)
const service = axios.create({
  baseURL: '',
  timeout: 5000
})

/**
 * @description 请求拦截器
 */
// const globalStore = GlobalStore()
service.interceptors.request.use(
  (config) => {
    // let token = ''
    // if (localStorage.getItem('token') && sessionStorage.getItem('newToken')) {
    //   if (
    //     sessionStorage.getItem('newToken') === localStorage.getItem('token')
    //   ) {
    //     token = localStorage.getItem('token')
    //   } else {
    //     token = sessionStorage.getItem('newToken')
    //   }
    // } else {
    //   token = localStorage.getItem('token')
    // }
    // // localStorage.setItem('token', newToken)
    // config.headers.Authorization = 'Bearer ' + token || ''
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

/**
 * @description 响应拦截器
 */
service.interceptors.response.use(
  (response) => {
    const res = response.data
    if (res instanceof Blob) {
      // 流文件
      return res
    }
    if (Number(res.code) !== 200) {
      ElMessage({
        message: res.msg || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(new Error(res.msg || 'Error'))
    } else {
      return res
    }
  },
  (error) => {
    // if (error.response?.data?.code === 401) {
    //   if (localStorage.getItem('hasError401') === '1') {
    //     router.push('/login')
    //   } else {
    //     localStorage.setItem('hasError401', '1')
    //     ElMessage({
    //       message: 'Login failed, please log in again',
    //       type: 'error',
    //       duration: 2 * 1000
    //     })
    //     router.push('/login')
    //   }
    // } else {
    //   ElMessage({
    //     message: 'The service is unavailable',
    //     type: 'error',
    //     duration: 2 * 1000
    //   })
    // }
    return Promise.reject(error)
  }
)

export default service
